Skip to content

This is about const keyword in various situations [pointers and refernces ]#7

Open
Butcher3Years wants to merge 1 commit intostring---literalsfrom
Const--types
Open

This is about const keyword in various situations [pointers and refernces ]#7
Butcher3Years wants to merge 1 commit intostring---literalsfrom
Const--types

Conversation

@Butcher3Years
Copy link
Copy Markdown
Owner

🔗 C++ Const + References: Complete Memory Safety Guide

Const Pointer Types

Type Syntax Data Change? Pointer Rebind?
Pointer to const const int* ptr ❌ No ✅ Yes
Const pointer int* const ptr ✅ Yes ❌ No
Both const const int* const ptr ❌ No ❌ No

References + Const Mastery

int x = 10, y = 20;

// 1. Regular reference (must bind to lvalue)
int& ref1 = x;     // ref1 IS x ✓ Can modify x via ref1
ref1 = 30;         // x becomes 30

// 2. Const reference (read-only view)
const int& ref2 = x;  // ref2 sees x, can't modify
// ref2 = 40;        // ERROR!

// 3. Const ref extends lifetimes (temporary binding)
const int& ref3 = 5;  // Binds to rvalue, lives until ref3 destroyed

// 4. Function params (industry standard)
void print(const int& val) { cout << val; }  // Safe, efficient

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant